'''
Script for downloading audio from vk.com playlists.

You should pass html file with playlist as first argument, like this:

python3 vk_downloader.py audio.html

and it will print to standart output wget commands for downloading. 

To run this commands, execute:

python3 vk_downloader.py audio.html | sh
'''
import sys

from lxml import html
from lxml import etree

def clear_param(txt):
    return txt.strip().replace('"', r'\"')

def parse(fl):
    tree = html.parse(fl)
    elements = tree.xpath('//div[@id="initial_list"]//input')
    urls = []
    for el in elements:
        urls.append(el.attrib['value'].split(',')[0])

    elements = tree.xpath('//div[@id="initial_list"]//div[@class="title_wrap fl_l"]')
    for el, url in zip(elements, urls):
        performer = clear_param(el.xpath('b/a/text()')[0])
        title = clear_param(el.xpath('span[@class="title"]//text()')[0])
        print('wget -c -O "{performer} - {title}.mp3" "{url}"'.format(
            url=url, performer=performer, title=title
        ))

def main():
    if len(sys.argv) > 1:
        parse(sys.argv[1])
    else:
        print('Pass file name', file=sys.stderr)


if __name__=='__main__':
    main()
